package com.midele.goodstuff.ui.main.screen

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.midele.goodstuff.R
import com.midele.goodstuff.navigation.MidNavHost
import com.midele.goodstuff.navigation.recordFirstRoute
import com.midele.goodstuff.ui.theme.Black12
import com.midele.goodstuff.viewmodel.RecordViewModel


// 菜单项数据模型
data class MenuItem(
    val id: String,
    val title: String
)

// Grid 项数据模型
data class GridItem(
    val id: String,
    val imageUrl: String, // 简单的图片 URL 或本地资源 ID
    val title: String,
    val category: String // 用于根据菜单切换过滤
)

// 模拟菜单数据
val sampleMenuItems = listOf(
    MenuItem("cat1", "Category 1"),
    MenuItem("cat2", "Category 2"),
    MenuItem("cat3", "All Items")
)

// 模拟 Grid 数据
val sampleGridItems = listOf(
    GridItem("item1", "https://picsum.photos/seed/picsum1/200/300", "Nature Walk", "cat1"),
    GridItem("item2", "https://picsum.photos/seed/picsum2/200/300", "City Lights", "cat2"),
    GridItem("item3", "https://picsum.photos/seed/picsum3/200/300", "Mountain View", "cat1"),
    GridItem("item4", "https://picsum.photos/seed/picsum4/200/300", "Beach Sunset", "cat2"),
    GridItem("item5", "https://picsum.photos/seed/picsum5/200/300", "Forest Trail", "cat1"),
    GridItem("item6", "https://picsum.photos/seed/picsum6/200/300", "Urban Exploration", "cat2"),
    GridItem("item7", "https://picsum.photos/seed/picsum7/200/300", "Desert Oasis", "cat1"),
    GridItem("item8", "https://picsum.photos/seed/picsum8/200/300", "Skyline at Night", "cat2"),
)

@Composable
internal fun RecordRoute(
    modifier: Modifier = Modifier,
    viewModel: RecordViewModel = hiltViewModel(),
    navController: NavHostController,
) {

    RecordScreen(viewModel,navController)
}

@Composable
fun RecordScreen(viewModel: RecordViewModel,navController: NavHostController) {

    var selectedMenuItemId by remember { mutableStateOf(sampleMenuItems.first().id) }

    ConstraintLayout(modifier = Modifier.fillMaxSize()) {
        val (leftTitleLayout, rightTrashLayout, tagMenuLayout, gridContentLayout) = createRefs()

        Text(
            text = "权属登记",
            color = Color.White,
            fontSize = 18.sp,
            style = MaterialTheme.typography.headlineLarge,
            modifier = Modifier.constrainAs(leftTitleLayout) {
                top.linkTo(parent.top, 54.dp)
                start.linkTo(parent.start, 20.dp)
            }
        )

        IconTextRow(
            iconId = R.mipmap.ic_trash_white,
            text = "草稿箱",
            modifier = Modifier.constrainAs(rightTrashLayout) {
                top.linkTo(parent.top, 54.dp)
                end.linkTo(parent.end, 10.dp)
            }
        )

        // 1. 左侧菜单列表
        MenuList(
            items = sampleMenuItems,
            selectedItemId = selectedMenuItemId,
            onItemSelected = { newItemId ->
                selectedMenuItemId = newItemId
            },
            modifier = Modifier.constrainAs(tagMenuLayout) {
                top.linkTo(leftTitleLayout.bottom, 20.dp)
                start.linkTo(parent.start)
                bottom.linkTo(parent.bottom)
                width = Dimension.percent(0.3f) // 宽度填充到约束（即到引导线）
                height = Dimension.fillToConstraints
            }
        )

        // 3. 右侧内容 Grid
        ContentGrid(
            items = sampleGridItems.filter {
                // 根据选择的菜单项过滤 Grid 内容
                if (selectedMenuItemId == "cat3") true // "All Items"
                else it.category == selectedMenuItemId
            },
            modifier = Modifier.constrainAs(gridContentLayout) {
                top.linkTo(leftTitleLayout.bottom, 20.dp)
                start.linkTo(tagMenuLayout.end, margin = 0.dp) // 开始于菜单列表的结束
                end.linkTo(parent.end)
                bottom.linkTo(parent.bottom)
                width = Dimension.percent(0.7f) // 宽度填充到约束（即从 menuList.end 到 parent.end）
                // 如果 menuList 的宽度是百分比，这里也会自动适应剩余百分比
                height = Dimension.fillToConstraints
            },
            onItemSelected = {
                navController.navigate(recordFirstRoute)
            }
        )
    }


}

@Composable
fun IconTextRow(
    iconId: Int,
    text: String,
    modifier: Modifier = Modifier,
    iconSize: Dp = 24.dp,
    spacing: Dp = 4.dp,
    contentDescription: String? = null // For accessibility
) {
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically, // 垂直居中对齐图标和文字
        horizontalArrangement = Arrangement.Start // 水平方向从左到右排列
    ) {
        Text(
            text = text,
            style = MaterialTheme.typography.bodyLarge // 使用主题的文本样式
        )
        Spacer(modifier = Modifier.width(spacing)) // 图标和文字之间的间距
        Image(
            painter = painterResource(id = iconId),
            contentDescription = contentDescription, // Important for accessibility
            modifier = Modifier.size(iconSize)
        )
    }
}

@Composable
fun MenuList(
    items: List<MenuItem>,
    selectedItemId: String,
    onItemSelected: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .fillMaxHeight()
            .background(Black12)
            .padding(8.dp)
    ) {
        items.forEach { item ->
            Button(
                onClick = { onItemSelected(item.id) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 4.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = if (item.id == selectedItemId) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant,
                    contentColor = if (item.id == selectedItemId) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant
                )
            ) {
                Text(item.title)
            }
        }
    }
}

@Composable
fun ContentGrid(
    items: List<GridItem>,
    modifier: Modifier = Modifier,
    onItemSelected: (String) -> Unit
) {
    if (items.isEmpty()) {
        Box(
            modifier = modifier
                .fillMaxSize()
                .padding(16.dp), contentAlignment = Alignment.Center
        ) {
            Text("No items to display for this category.")
        }
        return
    }

    LazyVerticalGrid(
        columns = GridCells.Fixed(2), // 限制为两列
        modifier = modifier
            .fillMaxSize()
            .padding(8.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        content = {
            items(items.size) { itemPosition ->
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(153.dp)
                        .clickable {
                            onItemSelected(items[itemPosition].id)
                        }
                        .background(color = Color(0xFF211C18), shape = RoundedCornerShape(16.dp)),
                    contentAlignment = Alignment.Center
                ) {

                    Image(
                        painter = painterResource(id = R.drawable.ic_good_demo), // 替换为你的图片资源ID
                        contentDescription = "Logo Image", // 图片描述，对于无障碍很重要
                        contentScale = ContentScale.Crop, // 图片填充模式，根据你的需求选择合适的模式
                        modifier = Modifier
                            .clip(RoundedCornerShape(10.dp))
                            .size(110.dp)
                            .padding(6.dp)

                    )

                    Text(
                        text = "至纯天珠",
                        color = Color.White,
                        fontSize = 14.sp,
                        modifier = Modifier
                            .padding(top = 125.dp)
                    )


                }
            }
        }
    )
}
